<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\VerifyCode;
use think\Db;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class Auth extends Api
{
    protected $noNeedLogin = ['sendCode', 'register', 'login', 'sendPayPasswordCode'];
    protected $noNeedRight = '*';

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {

    }

    /**
     * 发送验证码
     * 
     * @ApiMethod (POST)
     * @ApiParams (name="phone", type="string", required=true, description="手机号")
     * @ApiParams (name="type", type="string", required=false, description="验证码类型，可不传，默认为register")     
     */
    public function sendCode()
    {
        $phone = $this->request->param('phone');
        $type = $this->request->param('type', 'register');

        if (!$phone || !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $this->error('请输入正确的手机号');
        }

        $verifyCodeModel = new VerifyCode();
        $result = $verifyCodeModel->sendCode($phone, $type);

        if ($result['code']) {
            $this->success($result['msg'], $result['data']);
        } else {
            $this->error($result['msg']);
        }
    }
    
    /**
     * 发送支付密码验证码
     * 
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="type", type="string", required=false, description="验证码类型，可选值：pay_password(设置支付密码)、reset_pay_password(重置支付密码)，默认为pay_password")     
     */
    public function sendPayPasswordCode()
    {
        $mobile = $this->request->param('mobile');
        // 兼容phone参数名
        if (!$mobile) {
            $mobile = $this->request->param('phone');
        }
        $type = $this->request->param('type', 'pay_password');
        
        // 验证类型
        if (!in_array($type, ['pay_password', 'reset_pay_password'])) {
            $this->error('验证码类型不正确');
        }

        if (!$mobile || !preg_match('/^1[3-9]\d{9}$/', $mobile)) {
            $this->error('请输入正确的手机号');
        }

        // 记录日志，方便调试
        \think\Log::write("发送支付密码验证码: 手机号:{$mobile}, 类型:{$type}", 'info');
        
        $verifyCodeModel = new VerifyCode();
        $result = $verifyCodeModel->sendCode($mobile, $type);

        if ($result['code']) {
            // 记录成功日志
            \think\Log::write("支付密码验证码发送成功: 手机号:{$mobile}, 类型:{$type}", 'info');
            $this->success($result['msg'], $result['data']);
        } else {
            // 记录失败日志
            \think\Log::write("支付密码验证码发送失败: 手机号:{$mobile}, 类型:{$type}, 错误:{$result['msg']}", 'error');
            $this->error($result['msg']);
        }
    }

    /**
     * 用户注册
     */
    public function register()
    {
        $phone = $this->request->param('phone');
        $code = $this->request->param('code');
        $inviteCode = $this->request->param('invite_code', '');

        // 验证参数
        if (!$phone || !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $this->error('请输入正确的手机号');
        }
        if (!$code) {
            $this->error('请输入验证码');
        }

        // 验证验证码
        $verifyCodeModel = new VerifyCode();
        $verifyResult = $verifyCodeModel->verifyCode($phone, $code, 'register');
        if (!$verifyResult['code']) {
            $this->error($verifyResult['msg']);
        }

        // 检查用户是否已存在
        $userExists = Db::name('user')->where('mobile', $phone)->find();
        if ($userExists) {
            $this->error('该手机号已被注册');
        }

        // 开始事务
        Db::startTrans();
        try {
            // 创建用户
            $userId = Db::name('user')->insertGetId([
                'mobile' => $phone,
                'invite_code' => $inviteCode,
                'status' => 1,
                'createtime' => time(),
                'updatetime' => time()
            ]);

            // 生成推广码 (6位随机字母数字组合)
            $promotionCode = $this->generatePromotionCode();

            // 更新用户的推广码
            Db::name('user')->where('id', $userId)->update([
                'promotion_code' => $promotionCode,
                'updatetime' => time()
            ]);

            // 如果有邀请码，处理邀请关系
            if ($inviteCode) {
                // 查询邀请码是否存在
                $inviter = Db::name('user')->where('promotion_code', $inviteCode)->find();
                if (!$inviter) {
                    throw new \Exception('绑定用户不存在');
                }
                // 更新当前用户的parent_id
                Db::name('user')->where('id', $userId)->update([
                    'parent_id' => $inviter['id'],
                    'updatetime' => time()
                ]);
            }

            Db::commit();
            // 替换 $this->success 为直接返回JSON
            return json([
                'code' => 1,
                'msg' => '注册成功',
                'data' => ['user_id' => $userId]
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 用户登录
     */
    public function login()
    {
        $phone = $this->request->param('phone');
        $code = $this->request->param('code');

        // 验证参数
        if (!$phone || !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $this->error('请输入正确的手机号');
        }
        if (!$code) {
            $this->error('请输入验证码');
        }

        // 验证验证码
        $verifyCodeModel = new VerifyCode();
        $verifyResult = $verifyCodeModel->verifyCode($phone, $code, 'login');
        if (!$verifyResult['code']) {
            $this->error($verifyResult['msg']);
        }

        $user = Db::name('app_user')->where('mobile', $phone)->find();
        
        if (!$user) {
            $this->error('用户不存在，请先注册');
        }

        // 4. 更新最后登录时间
        $nowTime = time();
        Db::name('app_user')->where('id', $user['id'])->update([
            'last_login_time' => $nowTime
        ]);

        // 使用FastAdmin Auth类进行登录
        $userInfo =$this->auth->direct($user['id']);
        // 显式设置用户对象到Auth实例
        $this->auth->user = $user;
        // 更新最后登录时间
        Db::name('app_user')->where('id', $user['id'])->update(['last_login_time' => time()]);

        // 获取FastAdmin生成的token和过期时间
        $token = $this->auth->getToken();
        $userInfo = $this->auth->getUserInfo();
        $expireTime = time() + 86400; // 24小时有效期

        // 7. 返回登录结果
        $this->success('登录成功', [
            'token' => $token,
            'expire_time' => $expireTime,
            'user' => [
                'id' => $user['id'],
                'mobile' => $user['mobile'],
                'username' => $user['nickname'],
                'last_login_time' => $nowTime
            ]
        ]);
    }

    

    /**
     * 生成唯一token
     */
    private function generateToken($userId)
    {
        return md5(uniqid() . $userId . mt_rand(100000, 999999) . time());
    }

    /**
     * 生成唯一的推广码
     * @return string
     */
    private function generatePromotionCode()
    {
        $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $codeLength = 6;
        $promotionCode = '';
        for ($i = 0; $i < $codeLength; $i++) {
            $promotionCode .= $chars[mt_rand(0, strlen($chars) - 1)];
        }

        // 检查推广码是否已存在
        $exists = Db::name('app_user')->where('promotion_code', $promotionCode)->find();
        if ($exists) {
            // 如果已存在，递归生成新的推广码
            return $this->generatePromotionCode();
        }

        return $promotionCode;
    }
}